package com.mobilepay.moneypig.model.activity.mine;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.base.NoDoubleClickListener;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.activity.launcher.LoginActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.timecount.CodeTimerService;
import com.mobilepay.moneypig.timecount.CountDownTimerUtil;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.PreferenceUtil;

/**
 * Created by xlm on 2017/7/27 0027
 */

public class ChangeMobileActivity extends BaseActivity {
    private static final String TAG = "ChangeMobileActivity";
    private ImageView mImageBack;
    private EditText mEditMobile;
    private EditText mEditCode;
    private EditText mEditPassword;
    private TextView mTextButton;
    private Button mButtonChange;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_change_mobile);
    }

    @Override
    protected void initViews() {
        mImageBack = (ImageView) findViewById(R.id.mobile_back);
        mEditMobile = (EditText) findViewById(R.id.mobile_number);
        mEditCode = (EditText) findViewById(R.id.mobile_code);
        mEditPassword = (EditText) findViewById(R.id.mobile_password);
        mTextButton = (TextView) findViewById(R.id.mobile_button);
        mButtonChange = (Button) findViewById(R.id.mobile_change);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {

    }

    // 注册广播
    private static IntentFilter updateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CodeTimerService.IN_RUNNING);
        intentFilter.addAction(CodeTimerService.END_RUNNING);
        return intentFilter;
    }

    String sMobile;
    // 广播接收者
    private final BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case CodeTimerService.IN_RUNNING:
                    if (mTextButton.isEnabled())
                        mTextButton.setEnabled(false);
                    // 正在倒计时
                    sMobile = intent.getStringExtra("mobile");
                    mEditMobile.setText(sMobile);
                    mEditMobile.setSelection(sMobile.length());
                    mTextButton.setText(intent.getStringExtra("time"));
                    break;
                case CodeTimerService.END_RUNNING:
                    // 完成倒计时
                    mTextButton.setEnabled(true);
                    mTextButton.setText("获取验证码");
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // 注册广播
        registerReceiver(mUpdateReceiver, updateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 移除注册
        unregisterReceiver(mUpdateReceiver);
    }

    @Override
    protected void onSetListener() {
        mImageBack.setOnClickListener(this);
        mTextButton.setOnClickListener(this);
        mButtonChange.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                super.onNoDoubleClick(view);
                checkData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mobile_back:
                finish();
                break;
            case R.id.mobile_button:
                checkCode();
                break;
        }
    }

    private void checkData() {
        String mobile = mEditMobile.getText().toString();
        String code = mEditCode.getText().toString();
        String password = mEditPassword.getText().toString();
        if (CommonUtil.isEmpty(mobile)) {
            showToastShort("请输入手机号");
        } else if (CommonUtil.isEmpty(code)) {
            showToastShort("请输入验证码");
        } else if (CommonUtil.isEmpty(password)) {
            showToastShort("请输入登陆密码");
        } else {
            if (!CommonUtil.isMobile(mobile)) {
                showToastShort("请输入正确的手机号");
            } else {
                if (PreferenceUtil.getParam(getThis(), Key.PASSWORD, "").equals(password)) {
                    changeMobile();
                } else {
                    showToastShort("登录密码错误");
                }
            }
        }
    }

    private void checkCode() {
        String mobile = mEditMobile.getText().toString();
        if (CommonUtil.isEmpty(mobile)) {
            showToastShort("请输入手机号");
        } else {
            if (!CommonUtil.isMobile(mobile)) {
                showToastShort("请输入正确的手机号");
            } else {
                getYzCode();
            }
        }
    }

    /**
     * 获取验证码
     */
    private void getYzCode() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.sendsms);
        param.add("mobile", mEditMobile.getText().toString());
        param.add("sign", param.getMd5String());
        showProgress("验证码发送中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(result.getInfo());
                    if (result.getStatus() == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Intent intent = new Intent();
//                                intent.setClass(ChangeMobileActivity.this, CodeTimerService.class);
//                                intent.putExtra("mobile", mEditMobile.getText().toString());
//                                startService(intent);
                                new CountDownTimerUtil(mTextButton, NetConfig.cutdown_time, 1000).start();
                            }
                        });
                    }
                }
            }
        });
    }

    private void changeMobile() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.mobile_bind);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("username", mEditMobile.getText().toString());
        param.add("verify", mEditCode.getText().toString());
        param.add("password", mEditPassword.getText().toString());
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(responseResult.getInfo());
                    if (responseResult.getStatus() == 1) {
                        savaMobile();
                    }
                }
            }
        });
    }

    //保存手机号
    private void savaMobile() {
        String mobile = mEditMobile.getText().toString();
        PreferenceUtil.setParam(getThis(), Key.USERNAME, mobile);
        Intent intent = new Intent();
        intent.setClass(ChangeMobileActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finishActivity(true);//返回
    }
}
